import React, { Component } from 'react'
import { Button } from 'antd';
import { PlusOutlined, DeleteOutlined } from '@ant-design/icons';
import {connect} from 'react-redux';
import axios from "axios";
import { Table, message, Modal, Input  } from 'antd';

class Todo extends Component {
  componentDidMount(){
    if(this.props.datalist.length===0){
      this.props.setList()
    }
  }
  onUpdate = (item)=>{    
    return axios.put(`http://localhost:8000/list/${item.id}`,{
      ...item,
      isDone:!item.isDone
    }).then(res=>{ 
    })
  }
  onDelete = (item) => {
    axios.delete(`http://localhost:8000/list/${item.id}`).then(res=>{ 
      message.success('删除成功！');
    })
  }
  onAdd = ()=>{    
    this.setState({
      visible: true,
    });
  }

  handleOk = e => {
    console.log(this.state.newThing);
    this.setState({
      visible: false,
    });
    axios.post(`http://localhost:8000/list`,{
      name:this.state.newThing,
      isDone:false
    }).then(res=>{ 
    })
  };

  handleCancel = e => {
    console.log(e);
    this.setState({
      visible: false,
    });
  };
  onChange = e => {
    const { value } = e.target;
    this.setState({
      newThing: value
    })
  };
  state = {
    newThing:"",
    visible: false,
    columns : [
      {
        title: '#', //列的名字
        dataIndex: 'id', //对应原始数据中 .属性
        id: 'id',
        render:item=>{
          return <b>{item}</b>
        }
      },
      {
        title: '事件名称', //列的名字
        dataIndex: 'name', //对应原始数据中 .属性
        id: 'name',
      },
      {
        title: '编辑',
        key: 'action',
        render: (item) => (<div>  
          <Button type="primary" onClick={ ()=>this.onUpdate(item) }> 
              置为已办
          </Button>   
          <Button type="primary" danger shape="circle" icon={<DeleteOutlined />} onClick={ ()=>this.onDelete(item) } />
        </div>
        ),
      },
    ]
  }
  render() {
    return (
      <div>
        <Button type="primary" icon={<PlusOutlined />} onClick={ ()=>this.onAdd() } >
          新增待办事项
        </Button>
        <Table
          rowKey={item => item.id } 
          columns={this.state.columns}
          dataSource={this.props.datalist}
          pagination = { {pageSize:10} }
        />

        <Modal
          title="新增待办事项"
          visible={this.state.visible}
          onOk={this.handleOk}
          onCancel={this.handleCancel}
          okText="确认"
          cancelText="取消"
        >
          <Input placeholder="输入待办事项名称" onChange={this.onChange} />
        </Modal>
      </div>
    )
  }
}
const mapStateToProps = (state)=>{
  return {
    datalist:state.todoList.filter(item=>!item.isDone)
  }
}
const mapDispatchToProps  = {
  setList:()=>{
    return axios.get(`http://localhost:8000/list`).then(res=>{       
      return {
        type:"SetTodoList",
        payload:res.data
      }
    })
  }
}
export default connect(mapStateToProps, mapDispatchToProps)(Todo)